import React, { useState } from 'react'
import { EyeInvisibleOutlined, EyeTwoTone, SafetyCertificateOutlined, UnlockOutlined, UserOutlined } from '@ant-design/icons'
import { Button, Form, Input, message, Row } from 'antd'
import { LoginInfo as LoginParamsType } from '../../typings/login'
import { ProjectName, StoreKey } from '@/common/constants'
import { useNavigate } from 'react-router-dom'
import { useStore } from '@/store'
import logo from '@/assets/logo.svg'
import code from '@/assets/login-code.png'
import { useTitle } from 'ahooks'
import './login.less'

const Login = () => {
  const [form] = Form.useForm<{ username: string; password: string; vercode: string }>()
  const [loading, setLoading] = useState(false)
  const { userStore } = useStore()
  const navigate = useNavigate()
  const rules = {
    username: [
      { required: true, message: '请填写用户名', trigger: 'blur' },
      { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请填写密码', trigger: 'blur' },
      { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
    ],
    vercode: [{ required: true, message: '请填写验证码', trigger: 'blur' }],
  }
  useTitle(`登录 - ${ProjectName}`)

  const { validateFields } = form
  const onFinish = () => {
    validateFields()
      .then(async (values: LoginParamsType) => {
        const params = Object.assign(values, { key: '1111' })

        userStore.login(params).then(async (response) => {
          if (response) {
            localStorage.setItem(StoreKey, JSON.stringify(response))
            await userStore.getInfo()

            navigate('/basic/dashboard')

            // 延迟 1 秒显示欢迎信息
            setTimeout(() => {
              message.success('Hi, 欢迎回来')
            }, 1000)
          }
        }).catch((error: any) => {
          console.log('error', error)
          handleCaptcha()
          setLoading(false)
        })
      })
      .catch((error: any) => {
        console.log('error', error)
        setLoading(false)
      })
  }

  const handleCaptcha = () => {
    // setCaptch(code)
  }

  return (
    <div className="app-login">
      <Form
        className="app-login-form"
        layout="horizontal"
        form={form}
        onFinish={onFinish}
        initialValues={{
          username: 'admin',
          password: '123456',
          vercode: 'HWFB',
        }}
      >
        <h1>
          <img style={{ width: '60px' }} src={logo} alt={ProjectName} /> {ProjectName}
        </h1>
        <Form.Item name="username" rules={rules.username} hasFeedback>
          <Input size="large" autoComplete="off" prefix={<UserOutlined />} placeholder="用户名" />
        </Form.Item>
        <Form.Item name="password" rules={rules.password} hasFeedback>
          <Input.Password
            autoComplete="off"
            size="large"
            prefix={<UnlockOutlined />}
            placeholder="密码"
            iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
          />
        </Form.Item>
        <Form.Item className="imgcode-item">
          <Form.Item name="vercode" rules={rules.vercode}>
            <Input
              className="captch-input"
              size="large"
              maxLength={4}
              autoComplete="off"
              prefix={<SafetyCertificateOutlined />}
              placeholder="图形验证码"
            />
          </Form.Item>
          <span className="captch-wrap" onClick={handleCaptcha}>
            <img src={code} className="captcha" title="图形验证码" alt="图形验证码" />
          </span>
        </Form.Item>
        <Row>
          <Button block size="large" type="primary" htmlType="submit" loading={loading}>登录</Button>
        </Row>
      </Form>
    </div>
  )
}

export default Login
